import DeliverApi from '../../../common/api/breedsales/deliverbills.api.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { Select2Page } from "../../../common/serve-request.js";
(function (window, document, $) {
    let _vm, savetype, entriesmater, getEntryInfo = [], nextEntryId = 1, operaEntryId, saveEntry, _specLevelArry = [];
    const BaseCfgURL = Utils.CurDomain.BreedURL;
    $(function () {
        _vm = new Vue({
            el: "#saleordersentry-form",
            data() {
                return {
                    "entries": [
                        {
                            "seq": 0,
                            "farmOrgId": "",
                            "farmOrgName": "",
                            "deiverId": "",
                            "deiverName": "",
                            "deiverNumCode": "",
                            "deiverPhone": "",
                            "shipRegion": "",
                            "shipAddress": "",
                            "deliveryRegion": "",
                            "deliveryAddress": "",
                            "specLevel": "",
                            "carNo": "",
                            "transferCarNo": "",
                            "count": 0,
                            "unitPrice": 0,
                            "weight": 0,
                            "isGift": false,
                            "materialId": "",
                            "materialName": "",
                            "materialNumCode": "",
                            "baseMeasureUnit": "",
                            "subMeasureUnit": "",
                            "breedBatchId": "",
                            "breedBatchName": ""
                        }
                    ],
                    pickerData: []
                }
            },
            methods: {
                submit() {
                    //保留两位小数
                    const FLOAT_Method = /^\d+(\.\d{1,2})?$/;
                    //电话号码
                    const PHONE_VERIFICATION = /^1[3456789]\d{9}$/;

                    if (!Utils.IsNotNull($('#shipRegion').val())) {
                        return $.toptip(`请选择发货地址!`, 'warning');
                    }
                    if (!Utils.IsNotNull($('#shipAddress').val())) {
                        return $.toptip(`发货详细地址不能为空!`, 'warning');
                    }
                    //if (!Utils.IsNotNull($('#unitPrice').val())) {
                    //    return $.toptip(`单价不能为空!`, 'warning');
                    //}
                    //if (!(FLOAT_Method.test(($('#unitPrice').val())))) {
                    //    return $.toptip(`单价必须大于0且小数点后最多为两位!`, 'warning');
                    //}
                    if (!Utils.IsNotNull($('#deiverName').val())) {
                        return $.toptip(`司机姓名不能为空!`, 'warning');
                    }
                    if (!Utils.IsNotNull($('#deiverPhone').val())) {
                        return $.toptip(`司机电话号码不能为空!`, 'warning');
                    }
                    if (!(PHONE_VERIFICATION.test(($('#deiverPhone').val())))) {
                        return $.toptip(`请输入正确的电话号码!`, 'warning');
                    }
                    if (!Utils.IsNotNull($('#deliveryRegion').val())) {
                        return $.toptip(`收货地址不能为空!`, 'warning');
                    }
                    if (!Utils.IsNotNull($('#deliveryAddress').val())) {
                        return $.toptip(`收货详细地址不能为空!`, 'warning');
                    }
                    let details = $('#shipAddressPack').val().split("|");
                    if (!Utils.IsNotNull(details[0].split(';')[2])) {
                        return $.toptip(`发货地址至少选到区县!`, 'warning');
                    }
                    let delivery = $('#deliveryAddressPack').val().split("|");
                    if (!Utils.IsNotNull(delivery[0].split(';')[2])) {
                        return $.toptip(`收货地址至少选到区县!`, 'warning');
                    }

                    let isEdit = JSON.parse(getUrlKey('isEdit'))
                    let entries = {
                        "seq": isEdit ? parseInt(getUrlKey('index')) : parseInt(getUrlKey('index')) + 1,
                        "farmOrgId": $("#farmOrgId").select2('data')[0].id,// 农场ID
                        "farmOrgName": $("#farmOrgId").select2('data')[0].name, // 农场名称
                        "deiverId": "",
                        "deiverName": $(`#deiverName`).val(),
                        "deiverNumCode": "",
                        "deiverPhone": $(`#deiverPhone`).val(),
                        "shipRegion": $('#shipAddressPack').val(),
                        "shipAddress": $('#shipAddress').val(),
                        "deliveryRegion": $('#deliveryAddressPack').val(),
                        "deliveryAddress": $('#deliveryAddress').val(),
                        "specLevel": $('#specLevel').val(),
                        "carNo": $('#carNo').val(),
                        "transferCarNo": $('#transferCarNo').val(),
                        "count": $('#count').val(),
                        "unitPrice": $('#unitPrice').val() || 0,
                        "weight": $('#weight').val(),
                        "isGift": $("#isGift").prop("checked"),
                        "materialId": $(`#materialid`).select2('data')[0].id,
                        "materialName": $("#materialName").val(),
                        "materialNumCode": $("#materialNumCode").val(),
                        "baseMeasureUnit": $("#baseMeasureUnit").val(),
                        "subMeasureUnit": $(`#subMeasureUnit`).val(),
                        "breedBatchId": $(`#breedBatchId`).select2('data')[0].id,
                        "breedBatchName": $(`#breedBatchId`).select2('data')[0].text
                    }
                    savetips(entries)
                }
            }
        });

        _select2Info();
        _initCommand();
        _initAddressLoading();

        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式\
    });

    //加载行政区划数据
    const _initAddressLoading = () => {
        //获取行政区划信息
        DeliverApi.getDistricts().then(res => {
            _vm.pickerData = _getJsonTree(res, "e8wa")
        });
        //选择发货地址
        $(document).on('click', '#shipRegion', function () {
            weui.picker(_vm.pickerData, {
                onChange: function (result) {

                },
                onConfirm: function (result) {
                    let address = `${result[0].label}${result[1]?.label || ''}${result[2]?.label || ''}${result[3]?.label || ''}`;
                    let details = `${result[0].value};${result[1]?.value || ''};${result[2]?.value || ''};${result[3]?.value || ''}|${result[0].label};${result[1]?.label || ''};${result[2]?.label || ''};${result[3]?.label || ''}`;
                    $('#shipAddressPack').val(details)
                    $('#shipRegion').val(address)
                },
                id: 'multiPickerBtn'
            });
        });
        //选择收货地址
        $(document).on('click', '#deliveryRegion', function () {
            weui.picker(_vm.pickerData, {
                onChange: function (result) {

                },
                onConfirm: function (result) {
                    let address = `${result[0].label}${result[1]?.label || ''}${result[2]?.label || ''}${result[3]?.label || ''}`;
                    let details = `${result[0].value};${result[1]?.value || ''};${result[2]?.value || ''};${result[3]?.value || ''}|${result[0].label};${result[1]?.label || ''};${result[2]?.label || ''};${result[3]?.label || ''}`;
                    $('#deliveryAddressPack').val(details)
                    $('#deliveryRegion').val(address)
                }
            });
        });
    }

    // 初始化数据
    const _initCommand = () => {
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../deliverbills/order.html?v=${Utils.GetTime()}`;
        });

        //运输车牌
        $(`#carNo`).bind('input porpertychange', function () {
            $(`#carNo`).val($(`#carNo`).val().toUpperCase());
        });
        //中转车牌
        $(`#transferCarNo`).bind('input porpertychange', function () {
            $(`#transferCarNo`).val($(`#transferCarNo`).val().toUpperCase());
        });
    }

    //下拉框数据
    const _select2Info = async () => {
        //农场
        await DeliverApi.queryDepList(getUrlKey('orgId'), 1, '210').then(res => {
            $(`#farmOrgId`).select2({
                placeholder: '请选择农场...', //默认文字提示
                language: "zh-CN",//汉化
                data: res.map(item => {
                    return {
                        id: item.id,
                        numCode: item.numCode,
                        //text: `${item.name}(${item.numCode})`,
                        text: item.name,
                        name: item.name
                    }
                }),
            });
            $("#farmOrgId").setSelectValue();
        });
        //销售品类
        await requestDict(DictionaryType.LEVEL_TYPE).then(res => {
            _specLevelArry = res.data;
            $('#specLevel').select2({
                placeholder: '请选择销售品类...', //默认文字提示
                language: "zh-CN",//汉化
                data: res.data.map(item => {
                    return {
                        id: item.value,
                        text: item.displayName
                    }
                }),
            });
            $("#specLevel").setSelectValue();
            if (Utils.IsNotNull(_vm.entries[0].specLevel)) {
                $(`#specLevel`).setSelectValue(_vm.entries[0].specLevel);
            }

            // 养殖批次
            Select2Page($(`#breedBatchId`), `${BaseCfgURL}/breedbatchs/rlist`, (params) => {
                return JSON.stringify({
                    farmOrgId: $(`#farmOrgId`).val(),
                    fiOrgId: '',
                    tags: '',
                    name: '',
                    isEnd: false,
                    pageSize: 20,
                    pageIndex: (params.page || 1) - 1
                })
            }, "POST", {
                templateResult: function (res) {
                    return `${res.name == undefined ? res.text : res.name}`;
                }
            });

            if (Utils.IsNotNull(_vm.entries[0].breedBatchId)) {
                $(`#breedBatchId`).setSelectValue(_vm.entries[0].breedBatchId, _vm.entries[0].breedBatchName);
            }
        });
        //获取物料信息
        // $(`#materialid`).select2({
        //     language: "zh-CN",
        //     ajax: {
        //         url: `${Utils.CurDomain.MasterDataUrl}/yymaterials/q`,
        //         dataType: 'json',
        //         type: 'GET',
        //         headers: {
        //             Authorization: "Bearer " + Utils.GetSNAuthAT(),
        //             "Content-Type": 'application/json',
        //             Accept: 'application/json',
        //             "Access-Control-Allow-Origin": '*',
        //             "Access-Control-Allow-Headers": "X-Requested-With",
        //             "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS"
        //         },
        //         data: function (params) {
        //             return {
        //                 MGroupId: DictionaryType.MATERIAL_TYPE,
        //                 SearchInfo: params.term,
        //                 PageSize: 10,
        //                 PageIndex: (params.page || 1) - 1
        //             };
        //         },
        //         processResults: function (data, params) {
        //             params.page = params.page || 1;
        //             let _data = data.data.items.map(item => {
        //                 item.text = `${item.name}(${item.numCode})`;
        //                 return item;
        //             });
        //             return {
        //                 results: _data,// 后台返回的数据集
        //                 pagination: {
        //                     more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
        //                 }
        //             };
        //         },
        //         minimumInputLength: 1,
        //     }
        // });
        let allMaterial = await DeliverApi.postMaterial()
        let allMaterialInfo = allMaterial.items.filter(item => item.numCode.substring(0, 2) == '14')
        $(`#materialid`).select2({
            placeholder: '请选择物料...', //默认文字提示
            language: "zh-CN",//汉化
            data: allMaterialInfo.map(item => {
                return {
                    id: item.id,
                    text: `${item.name}(${item.numCode})`,
                    ...item
                }
            }),
        });


        $("#materialid").setSelectValue();
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let seq = getUrlKey('index')
        // 编辑时赋值
        if (isEdit) {
            let datas = getEntryInfo.find(item => item.seq == seq)
            $("#farmOrgId").setSelectValue(datas.farmOrgId)
            $("#breedBatchId").setSelectValue(datas.breedBatchId, datas.breedBatchName)
            $("#materialid").setSelectValue(datas.materialId, datas.materialName)
            $("#materialName").val(datas.materialName)
            $("#materialNumCode").val(datas.materialNumCode)
            $("#baseMeasureUnit").val(datas.baseMeasureUnit)
            $("#subMeasureUnit").val(datas.subMeasureUnit)

            $("#specLevel").setSelectValue(datas.specLevel)
            $("#count").setSelectValue(datas.count)
            $("#weight").setSelectValue(datas.weight)
            $("#carNo").setSelectValue(datas.carNo)
            $("#transferCarNo").setSelectValue(datas.transferCarNo)
            $('#deiverName').val(datas.deiverName);
            $('#deiverPhone').val(datas.deiverPhone);
            $('#transferCarNo').val(datas.transferCarNo);
            $('#unitPrice').val(datas.unitPrice);
            $('#isGift').prop('checked', datas.isGift);

            let address = await DeliverApi.getFarms(datas.farmOrgId);

            let details = datas.shipRegion?.split('|')[1].split(';');
            if (Utils.IsNotNull(details)) {
                $('#shipAddress').val(datas.shipAddress);
                $('#shipAddressPack').val(datas.shipRegion);
                $('#shipRegion').val(details[0] + details[1] + details[2] + details[3]);
            } else {
                let region = address.region.split('|')[1].split(';');
                $('#shipAddress').val(address.address);
                $('#shipAddressPack').val(address.region);
                $('#shipRegion').val(region[0] + region[1] + region[2] + region[3]);
            }

            let delivery = datas.deliveryRegion?.split('|')[1].split(';')
            $('#deliveryAddress').val(datas.deliveryAddress);
            if (Utils.IsNotNull(delivery)) {
                $('#deliveryRegion').val(delivery[0] + delivery[1] + delivery[2] + delivery[3]);
            }
            $('#deliveryAddressPack').val(datas.deliveryRegion);
        }
    }

    // 保存提示
    const savetips = (data) => {
        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
            savetype = '修改'
            saveEntry = getUrlKey("operaEntryId")
        }
        else {
            savetype = '保存'
            saveEntry = getUrlKey('nextEntryId')
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))
                        let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo")) || []

                        // 判断Sessions是否有数据  如果有 并且  不是修改分录
                        if (Utils.IsNotNull(entries) && isEdit == false) {
                            entries.push(data)
                        } else if (Utils.IsNotNull(entries) && isEdit) {
                            // 如果不为空且是修改
                            entries[seq == 0 ? 0 : seq - 1] = data

                        } else {
                            // 如果没有 并且不是修改分录
                            entries[0] = data
                        }
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getEntryInfo", entries))
                        location.href = `./order.html?v=${Utils.GetTime()}`;

                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    //递归
    const _getJsonTree = (data, parentId) => {
        var itemArr = [];
        for (var i = 0; i < data.length; i++) {
            var node = data[i];
            if (node.parent.id === parentId) {
                var newNode = {
                    value: node.id,
                    label: node.name,
                    children: _getJsonTree(data, node.id),
                };
                itemArr.push(newNode);
            }
        }
        return itemArr;
    }

})(window, document, jQuery)